package com.sanalkitaplik.usermanagement;

import java.util.ArrayList;

//import com.sanalkitaplik.hibernateutil.UsersUtil;

public class UserManagerBean {
	
	private User user;
	private boolean error;
	
	private static ArrayList<User> onlineUsers = new ArrayList<User>();
	
	private UserBookManager bookManager;
	
	public UserManagerBean() {
		user = new User();
		bookManager = new UserBookManager();
		error = false;
	}
	
	public UserBookManager getBookManager() {
		return bookManager;
	}
	
	public User getUser() {
		return user;
	}
	
	public String login() {
		String userName = user.getUserName();
		String password = user.getPassword();
		
		/*
		 * UsersUtil.loginCheck(userName, password) :
		 * Kullanıcı adı ve şifreyi veritabanından kontrol et, hatalıysa error = true yap.
		 */
		
		error = userName.isEmpty() || password.isEmpty();// || UsersUtil.loginCheck(userName, password);
		
		if (error) {
			return null; 
		}
		System.out.println("error yok");
		for (int i=0; i<UserManagerBean.onlineUsers.size(); i++) {
			if (UserManagerBean.onlineUsers.get(i) == this.user) {
				UserManagerBean.onlineUsers.remove(i);
				break;
			}
		}
		onlineUsers.add(user);
		return "userLoginSuccess";
	}
	
	public boolean getError() {
		return this.error;
	}
	
	public String logOut() {
		beOffline();
		return "userLoginPanel";
	}
	
	private void beOffline() {
		for (int i=0; i<UserManagerBean.onlineUsers.size(); i++) {
			if (UserManagerBean.onlineUsers.get(i).equals(this.user)) {
				UserManagerBean.onlineUsers.remove(i);
				return;
			}
		}
	}
	
	protected void finalize() {
		beOffline();
	}
	
	public static boolean isOnline(User user) {
		if (user == null)
			return false;
		for (int i=0; i<UserManagerBean.onlineUsers.size(); i++) {
			if (UserManagerBean.onlineUsers.get(i).equals(user))
				return true;
		}
		return false;
	}

}
